package daos.user.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import model.entities.User;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import daos.AbstractDAO;
import daos.user.UserAppDAO;

public class UserAppDAOJdbcTemplateImpl extends AbstractDAO implements
		UserAppDAO {

	private JdbcTemplate jdbcTemplate;

	public void insert(User user) throws SQLException {
		String insertSql = "INSERT INTO USERS (NAME, LOGIN, PASSWORD) VALUES (?,?,?)";
		Object[] parameters = { user.getName(), user.getLogin(),
				user.getPassword() };
		this.jdbcTemplate.update(insertSql, parameters);

		System.out.println(insertSql);
		System.out.println("Row inserted OK");
	}

	public void delete(User user) throws SQLException {
		String deleteSql = "DELETE FROM USERS WHERE NAME = ?";
		jdbcTemplate.update(deleteSql, user.getName());

		System.out.println(deleteSql);
		System.out.println("Row deleted OK");

	}

	public void update(User user) throws SQLException {
		String updateSql = "UPDATE USERS SET NAME = ?, PASSWORD = ? WHERE LOGIN = ?";
		Object[] parameters = { user.getName(), user.getPassword(),
				user.getLogin() };
		jdbcTemplate.update(updateSql, parameters);

		System.out.println(updateSql);
		System.out.println("Row updated OK");
	}

	public List<User> selectAll() throws SQLException {
		String selectSql = "SELECT * FROM USERS";
		List<User> userSeleccionados = jdbcTemplate.query(selectSql,
				getRowMapper());

		System.out.println(selectSql);
		System.out.println("Row selected OK");

		return userSeleccionados;
	}

	public List<User> selectByName(User user) throws SQLException {
		String selectSql = "SELECT * FROM USERS WHERE UPPER(NAME) LIKE ?";
		List<User> userSeleccionados = jdbcTemplate.query(selectSql,
				getRowMapper(), "%" + user.getName().toUpperCase() + "%");

		System.out.println(selectSql);
		System.out.println("Row selected OK");

		System.out.println(userSeleccionados);

		return userSeleccionados;
	}

	public boolean exist(User user) throws SQLException {
		String selectSql = "SELECT * FROM USERS WHERE LOGIN = ? AND PASSWORD = ?";
		Object[] parameters = { user.getLogin(), user.getPassword() };

		return !jdbcTemplate.query(selectSql, getRowMapper(), parameters).isEmpty();
	}

	public RowMapper<User> getRowMapper() {
		return new RowMapper<User>() {
			public User mapRow(ResultSet rs, int arg1) throws SQLException {
				User userSeleccionado = new User();

				userSeleccionado.setName(rs.getString("NAME"));
				userSeleccionado.setLogin(rs.getString("LOGIN"));
				userSeleccionado.setPassword(rs.getString("PASSWORD"));

				return userSeleccionado;
			}
		};
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
}
